<?php

if ( !class_exists( "BME_web" ) ) {
require_once( "Base.php" );
require_once( BME_ROOT . "util/pais.php" );

class BME_web extends BME_base {
	
	var $log;		// str	Log registry
	var $questo;		// str	Relative path to file
	var $cache_path;	// str	Path to cache file
	var $cache_timeout;	// int	Max time to recover a file from cache (on seconds)
	var $uncacheable;	// arr	Array of strings: 'questo' of non-cacheable files
	var $out;		// str	Content to show
	var $lang;		// str	Lang
	var $get;		// str	Get string for links
	var $allget;		// str	Get string for auto-links
	var $iNfo;		// arr	Array of str: names of lang:* conf vars to put on info boxes
	var $Warn;		// arr	Array of str: names of lang:* conf vars to put on warn boxes
	var $FErr;		// arr	Array of str: names of lang:* conf vars to put on ferr boxes
	var $_kill;		// bool	Must I die before show content?
	var $_restricted;	// int	I this page restricted? (0->No; 1->Yes, only users; 2->Yes, only Admins)
	var $restrictions;	// arr	Array of array of str: The restricted sites.
	var $hasFAQ;		// bool	Has an associated FAQ?
	var $downloads_path;	// str	Path to the downloads folder
	var $addedDicts;	// arr	Array of str: names of already uploaded dictionaries.
	
	/**
	 * bla_web new bla_web(str file);
	 * @param str file: The relative path (from BME_ROOT) to requested URI.
	 * @return bla_web (obj).
	 */
	function BME_web($file,$lang="") {
		assert('is_string($file)');
		assert('file_exists("'.BME_ROOT.$file.'.php")');
		$this->BME_base();
		register_BME_web($this);
		$this->_kill = false;
		
		// Tune BME_web
		$cache_dir = BME_ROOT."cache/";
		$this->cache_timeout = 15*(60*60*24); // 15 days
		$this->uncacheable = array(
			"blast",	// Each task is unique
			"virtual",	// ...
			"contact"	// Depends on the referer
		);
		$this->restrictions = array(1=>array("registro"), 2=>array("admin"));
		$this->allget = "";
		foreach ( $_GET as $k=>$v ) $this->allget.= "$k=$v&amp;";
		$this->allget = substr($this->allget,0,-5);
		
		// Lang
		if ( !in_array($lang,array("en","es")) ) $lang = "en";
		$this->lang = $lang;
		$this->get = "lang=".$this->lang;
		$this->addedDicts = array();
		
		// Paths
		$this->questo = $file;
		$this->proc_file = BME_ROOT."proc/{$this->questo}.php";
		$this->cache_path = $cache_dir.md5($GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI']);
		if(!$this->strict_cacheable()) $this->cache_path.= ".uc".time();
		$this->downloads_path = "downloads/";
		
		if ( in_array($this->questo,$this->restrictions[2]) ) $this->_restricted = 2;
		elseif ( in_array($this->questo,$this->restrictions[1]) ) $this->_restricted = 1;
		else $this->_restricted = 0;
		$this->hasFAQ = false;
		
		$this->add_dictionary("commons");
		
		// Log
		$country = country_by_ip($_SERVER['REMOTE_ADDR']);
		$this->log = "# ".BME_NAME." ".BME_VERSION."\n";
		$this->to_log(
			BME_NAME." started
			=== USR ===
			IP: {$_SERVER['REMOTE_ADDR']}
			Port: {$_SERVER['REMOTE_PORT']}
			Country: $country
			Agent: {$_SERVER['HTTP_USER_AGENT']}
			Language: {$_SERVER['HTTP_ACCEPT_LANGUAGE']}
			Referer: {$GLOBALS['HTTP_SERVER_VARS']['HTTP_REFERER']}
			=== SRV ===
			Server: {$GLOBALS['HTTP_SERVER_VARS']['SERVER_NAME']}
			URI: {$GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI']}
			Cache: {$this->cache_path}"
		);
	}
	/**
	 * void read_locale(void);
	 */
	function read_locale() {
		$this->add_dictionary($this->questo);
		return;
	}
	/**
	 * void add_dictionary(str dict);
	 * @param The dictionary name.
	 */
	function add_dictionary($dict) {
		assert('is_string($dict)');
		if ( in_array($dict,$this->addedDicts) ) return;
		assert('file_exists("'.BME_ROOT."locale/{$this->lang}/$dict.dict".'")');
		$this->conf_read_file( BME_ROOT."locale/{$this->lang}/$dict.dict","lang" );
		$this->addedDicts[] = $dict;
		return;
	}
	/**
	 * str locale(str k);
	 */
	function locale($k) {
		return $this->conf_get_var("lang:$k");
	}
	/**
	 * mix addbox(str title, mix content[, bool return[, str title_class]]);
	 * @param str title: The title for the box.
	 * @param mix content: An string containing just text (str); or an array containing each one a row,
	 *	\where data is parsed as table (arr).  The Array would contain any type of data, but if
	 *	\contains another array, the value for key 0 is parsed as a subtitle, and the value of the
	 *	\key 1 id parsed as content.
	 * @param bool return (optional): Must I add the box to the web's buffer (false) or must I return
	 *	\the generated HTML (true)?, false by default.
	 * @param str title_class (optional): Class of the title, "azul_hover" by default.
	 * @return mix: The HTML of the box if return is explicitly set to true.  Void else.
	 */
	function addBox($title, $content, $return=false, $title_class="azul_hover") {
		assert('is_string($title)');
		assert('!empty($title)');
		assert('is_array($content) | is_string($content)');
		assert('is_bool($return)');
		assert('is_string($title_class)');
		if ( is_string($content) ) $content = array($content);
		$id = md5($title).rand(0,99);
		$out = "";
		$out.= "
		<div class='explorer_box'>
                        <h2 class='$title_class' onclick='fold(\"{$id}_box\")' id='{$id}_'>$title</h2>
                        <table id='{$id}_box' cellspacing='0'>";
		foreach ( $content as $i ):
			if ( is_array($i) ):
				$out.= "
				<tr><td class='uno'>{$i[0]}</td><td>{$i[1]}</td></tr>";
			else:
				$out.= "
				<tr><td colspan='2'>{$i}</td></tr>";
			endif;
		endforeach;
		$out.= "
                        </table>
                </div>";
		if ( $return ) return $out;
		else $this->out.= $out;
		return;
	}
	/**
	 * void addinfo(str tok);
	 */
	function addInfo($tok) {
		if ( !is_array($this->iNfo) ):
			$this->add_dictionary("info");
			$this->iNfo = array();
		endif;
		assert('$this->conf_var_exists("lang:'.$tok.'")');
		$this->iNfo[] = $tok;
		return;
	}
	/**
         * void addwarn(str tok);
         */
        function addWarn($tok) {
                if ( !is_array($this->Warn) ):
                        $this->add_dictionary("warn");
                        $this->Warn = array();
                endif;
                assert('$this->conf_var_exists("lang:'.$tok.'")');
                $this->Warn[] = $tok;
		return;
        }
	/**
         * void addferr(str tok);
         */
        function addFErr($tok) {
                if ( !is_array($this->FErr) ):
                        $this->add_dictionary("ferr");
                        $this->FErr = array();
                endif;
                assert('$this->conf_var_exists("lang:'.$tok.'")');
                $this->FErr[] = $tok;
		return;
        }
	/**
	 * str getflags(void);
	 */
	function getFlags() {
		$out = "";
		if ( is_array($this->FErr) ): foreach ( $this->FErr as $i ):
			$out.= "<div class='flagFerr'><br/>".$this->locale($i)."<br/><br/></div>";
		endforeach; endif;
		if ( is_array($this->Warn) ): foreach ( $this->Warn as $i ):
			$out.= "<div class='flagWarn'><br/>".$this->locale($i)."<br/><br/></div>";
		endforeach; endif;
		if ( is_array($this->iNfo) ): foreach ( $this->iNfo as $i ):
			$out.= "<div class='flagInfo'><br/>".$this->locale($i)."<br/><br/></div>";
		endforeach; endif;
		return $out;
	}
	/**
	 * bool cacheable(void);
	 */
	function cacheable() {
		if($_GET["cache"]=="no") return false;
		if( !$this->strict_cacheable() ) return false;
		if( !file_exists($this->cache_path) ) return false;
		$ltime = filectime($this->cache_path) + $this->cache_timeout;
		if ( time() > $ltime ) return false;
		
		return true;
	}
	/**
	 * bool strict_cacheable(void);
	 */
	function strict_cacheable() {
		if ( in_array($this->questo, $this->uncacheable) ) return false;
		if ( in_array($this->questo, $this->restrictions[1]) ) return false;
		if ( in_array($this->questo, $this->restrictions[2]) ) return false;
		return true;
	}
	/**
	 * void savecache(void);
	 */
	function saveCache() {
		$fp = fopen($this->cache_path,"w") or $this->error("I can't save the file <b>".$this->cache_path."</b>");
		is_int(fwrite($fp, $this->out)) or $this->error("I can't write on <b>".$this->cache_path."</b>");
		fclose($fp);
		return;
	}
	/**
	 * void opencache(void);
	 */
	function openCache() {
		//$this->addInfo("cachedPage");
		global $__head__;
		$__head__.= "
		<script>
			myLineText='".$this->locale("cachedPage")."';
		</script>";
		return;
	}
	/**
	 * str blatags2html(str blaml);
	 * @param str blaml: Text with BLA tags (from BLA.id 0.3, modified for GeBiX).
	 * @return str: Text HTMLized.
	 */
	function blaTags2html($blaml) {
		assert('is_string($blaml)');
		require_once(BME_ROOT."Classes/Level.php");
		preg_match_all("/\[([a-z0-9]+):([^\/\s]+)\s*([^\]]*)\/\]/i",$blaml,$regs);
		foreach ( $regs[0] as $k=>$v ):
			$res = $v;
			$val = $regs[2][$k];
			$cnt = $regs[3][$k];
			switch(strtolower($regs[1][$k])):
				// General
				case 'external':
					switch ( strtolower($val) ):
						case 'embl':
							$XREF = explode(",",$cnt);
							$res = array();
							foreach ( $XREF as $xref ):
								$res[]= "<a href='http://www.ebi.ac.uk/cgi-bin/expasyfetch?$xref'>$val $xref</a>";
							endforeach;
							$res = implode(", ",$res);
						break;
						case 'uniprot':
							$XREF = explode(",",$cnt);
							$res = array();
							foreach ( $XREF as $xref ):
								$res[]= "<a href='http://www.uniprot.org/uniprot/$xref'>$val $xref</a>";
							endforeach;
							$res = implode(", ",$res);
						break;
						default:
							$res = "<a href='$cnt'>$val</a>";
						break;
					endswitch;
				break;
			endswitch;
			$blaml = str_replace($v,$res,$blaml);
		endforeach;
		return $blaml;
	}
	/**
	 * void to_log(str msg);
	 */
	function to_log($msg) {
		assert('is_string($msg)');
		foreach ( explode("\n",$msg) as $i ):
			$this->log.= date("Y-m-d H:i:s")." | ".trim($i)."\n";
		endforeach;
		return;
	}
	/**
	 * void __destruct(void);
	 */
	function __destruct() {
		$this->to_log("Finished");
		$fp = fopen(BME_ROOT.BME_NAME.".log", "a+") or $this->error("I can't open the log file.");
		fwrite($fp,$this->log);
		fclose($fp);
		return;
	}
	
}
function register_BME_web (&$BME_web) {
	global $___BME_web;
	$___BME_web = &$BME_web;
	return;
}
function shutting_down_BME() {
	return;
}
register_shutdown_function("shutting_down_BME");
}

?>
